package top.zhouze.common.data;

import android.util.Log;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import top.zhouze.common.util.ReflectUtil;

import java.util.concurrent.Executors;

public abstract class BaseDataRepository<A, D extends RoomDatabase> extends BaseRemoteRepository<A> {

    protected volatile D roomDatabase;

    protected Class<D> getDatabaseClass() {
        return ReflectUtil.getGenericClass(this, 1);
    }

    public D getRoomDatabase() {
        if (roomDatabase == null) {
            synchronized (this) {
                if (roomDatabase == null) {
                    roomDatabase = buildRoomDatabase();
                }
            }
        }
        return roomDatabase;
    }

    protected D buildRoomDatabase() {
        return getDatabaseBuilder().build();
    }


    protected RoomDatabase.Builder<D> getDatabaseBuilder() {
        return Room.databaseBuilder(getContext(), getDatabaseClass(), getDatabaseName(getDatabaseClass()));
    }

    protected void showSql(RoomDatabase.Builder<D> builder) {
        builder.setQueryCallback((sqlQuery, bindArgs) -> {
            if (!bindArgs.isEmpty()) {
                for (Object arg : bindArgs) {
                    if(arg.getClass().isArray()) {
                        sqlQuery = sqlQuery.replaceFirst("\\?", "null");
                    }else if (arg instanceof String) {
                        sqlQuery = sqlQuery.replaceFirst("\\?", "'"+arg+"'");
                    } else {
                        sqlQuery = sqlQuery.replaceFirst("\\?", String.valueOf(arg));
                    }
                }
            }
            Log.d("sql", sqlQuery);
        }, Executors.newSingleThreadExecutor());
    }

    protected String getDatabaseName(Class<D> databaseClass) {
        return getDatabaseClass().getSimpleName() + ".db";
    }
}
